<?php
/**
 * Created by PhpStorm.
 * User: 73640
 * Date: 2018/10/18
 * Time: 15:44
 */

namespace App\Repository;


use App\model\Workshop;

class WorkShopRepository
{
    /**
     * 园区列表
     *
     * @param  $request
     * city_id 城市
     * city_first_id 二级城市id
     * city_second_id 三级
     * area_id
     * sreach_key
     * 筛选条件
     * page_id 页码
     * 排序条件
     * sort_type  字段
     * 排序字段
     * sort 升序 降序
     *
     *link_model industry,propertyType,park
     */
    public function getList(array $request){
         $workshop=Workshop::with(['propertyType','park','broker'])-> leftJoin('park','workshop.park_id','=','park.id');
         if($request['type']!=2){
           $workshop=$workshop->where('workshop.type','=',$request['type']);
         }
         if(isset($request['city_id'])&&$request['city_id']!=0){
             $workshop=$workshop->Where('workshop.p_province_id',$request['city_id']);
         }
         if(isset($request['city_first_id'])&&$request['city_first_id']!=0){
             $workshop=$workshop->Where(
                 'p_city_id',$request['city_first_id']
             );
         }
        if(isset($request['city_second_id'])&&$request['city_second_id']!=0){
            $workshop=$workshop->Where(
                'p_district_id',$request['city_second_id']
            );
        }
        if(isset($request['area_id'])&&$request['area_id']!=0){
            $workshop=$workshop->where('workshop.area_id',$request['area_id']);
        }
        if(isset($request['search_key'])&&$request['search_key']!=''){
            $workshop=$workshop->where('workshop.title','like','%'.$request['search_key'].'%');
        }
        if(isset($request['sort_type'])&&$request['sort_type']!=''){
            $workshop=$workshop->orderBy('workshop.'.$request['sort_type'],$request['sort'] ?? 'asc');
        }else{
            $workshop=$workshop->orderBy('workshop.is_out','asc');
        }
        if(isset($request['is_recommend'])&&$request['is_recommend']!=''){
            $workshop=$workshop->where('is_recommend',$request['is_recommend']);
        }
        if(isset($request['link_model'])&&$request['link_model']!=''){
            $link_model = $request['link_model'];
            if(strpos($link_model,',')){
                $link_model = explode(',',$link_model);
            }else if(strpos($link_model,'，')){
                $link_model = explode('，',$link_model);
            }
            $workshop=$workshop->with($link_model);
        }

       $workshop=$workshop->select('workshop.*');
       $pagesize=$request['pagesize'] ?? 10;
       $workshop= $workshop->paginate($pagesize);
       return $workshop;
    }

    /**
     * @param int $workshop_id
     */
    public function detail(int $workshop_id){
        $workshop=Workshop::with(['park'=>function($query){
            $query->with(['parkType','parkFormat']);
        },'broker','propertyType'])->where('id',$workshop_id)->firstOrFail();
        return $workshop;
    }
}